<?php
 Class AdvertAction extends Action{
 	public function index(){
 		$Advert=M('Advert');
 		Import('ORG.Util.Page');
 		$count=$Advert->count();
 		$page=new Page($count,4);
 		$show=$page->show();
 		$rows=$Advert->limit($page->firstRow.','.$page->listRows)->select();
 		$this->assign('show',$show);
 		$this->assign('rows',$rows);
 		$this->display();
 	}
 	// 添加模版
 	public function add(){
 		$this->display();
 	}
 	// 添加操作
 	public function add_handle(){
 		
		import('ORG.Net.UploadFile');
		$upload = new UploadFile();// 实例化上传类
		$upload->maxSize  = 3145728 ;// 设置附件上传大小
		$upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
		$upload->savePath =  './Public/upload/';// 设置附件上传目录
		if(!$upload->upload()) {// 上传错误提示错误信息
		$this->error($upload->getErrorMsg());
		}else{// 上传成功 获取上传文件信息
		$info =  $upload->getUploadFileInfo();

		// 图片缩略 
		Import('ORG.Util.Image');
		$image=$info[0]['savepath'].$info[0]['savename'];//原图
		$thumb=$info[0]['savepath'].'t_'.$info[0]['savename'];//缩略图
		Image::thumb($image,$thumb,'','200','200');

		$_POST['img']=$info[0]['savename'];
		}

 		$Advert=M('Advert');
 		$pos=implode(',', $_POST['pos']);// 广告位置数组变成字符串
 		$_POST['pos']=$pos;
 		if($Advert->create()){
 			$Advert->add();
 			$this->redirect('index');
 		}else{
 			$this->error('添加失败');
 		};
 	}

 	// 删除
 	public function delete(){
 		$advert=M('Advert');
 		// 删除原图
 		$img='./Public/upload/'.$_GET['img'];
 		$t_img='./Public/upload/'.'t_'.$_GET['img'];
 		unlink($img);
 		unlink($t_img);
 		$id=$_GET['id'];
 		// 删除数据
 		if($advert->delete($id)){
 			$this->redirect('index');
 		}

 	}


 	// 修改模版
 	public function edit(){
 		$Advert=M('Advert');
 		$id=$_GET['id'];
 		$row=$Advert->find($id);
 		$this->assign('row',$row);
 		$this->display();
 	}
 	// 修改操作
 	public function edit_handle(){
 		$Advert=M('Advert');
 		
 		// 上传新图
 		Import('ORG.Net.UploadFile');
 		$upload= New UploadFile();
 		$upload->maxSize= '33556699';
 		$upload->allowExts=array('jpg','jpeg','png','gif');
 		$upload->savePath='./Public/upload/';
 		if($upload->upload()){
 			$info=$upload->getUploadFileInfo();
 			// 缩略图
 			Import('ORG.Util.Image');
 			$image=$info[0]['savepath'].$info[0]['savename'];
 			$thumb=$info[0]['savepath'].'t_'.$info[0]['savename'];
 			Image::thumb($image,$thumb,'','200','200');
 			$_POST['img']=$info[0]['savename'];

 			// 删除原图
 			$oldImg='./Public/upload/'.$_POST['imgsrc'];
 			$t_oldImg='./Public/upload/'.'t_'.$_POST['imgsrc'];
 			unlink($oldImg);
 			unlink($t_oldImg);
 		}
 		
 		// 重组位置信息，把数组变成字符串
 		$_POST['pos']= implode(',',$_POST['pos']);
 		if($Advert->create()){
 			$Advert->save();
 			$this->redirect('index');
 		};

 	}

 }
?>